package com.itjin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itjin.mapper.*;
import com.itjin.model.domain.dto.SendMessageDTO;
import com.itjin.model.domain.entity.*;
import com.itjin.model.domain.vo.MessageVO;
import com.itjin.model.domain.vo.PostCommentVO;
import com.itjin.model.domain.vo.PostVO;
import com.itjin.model.domain.vo.UserVO;
import com.itjin.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Slf4j
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageService {

  @Resource
  private MessageMapper messageMapper;

  @Resource
  private UserMapper userMapper;

  @Resource
  private PostMapper postMapper;

  @Resource
  private PostLikeMapper postLikeMapper;

  @Resource
  private PostCollectMapper postCollectMapper;

  @Resource
  private UserFollowMapper userFollowMapper;

  @Resource
  private PostCommentMapper postCommentMapper;

  @Override
  @Transactional
  public MessageVO sendMessage(Integer senderId, SendMessageDTO messageDTO) {
    try {
      // 1. 参数校验
      if (senderId == null || messageDTO == null) {
        throw new IllegalArgumentException("发送者ID和消息内容不能为空");
      }
      if (messageDTO.getReceiverId() == null) {
        throw new IllegalArgumentException("接收者ID不能为空");
      }
      if (messageDTO.getContent() == null || messageDTO.getContent().trim().isEmpty()) {
        throw new IllegalArgumentException("消息内容不能为空");
      }
      if (messageDTO.getMessageType() == null) {
        messageDTO.setMessageType(1); // 设置默认消息类型
      }

      // 2. 检查发送者和接收者是否存在
      User sender = userMapper.selectById(senderId);
      User receiver = userMapper.selectById(messageDTO.getReceiverId());
      if (sender == null) {
        throw new IllegalArgumentException("发送者不存在");
      }
      if (receiver == null) {
        throw new IllegalArgumentException("接收者不存在");
      }

      // 3. 生成会话ID (较小ID在前)
      String conversationId = generateConversationId(senderId, messageDTO.getReceiverId());

      // 4. 创建消息实体
      Message message = new Message();
      message.setConversationId(conversationId);
      message.setSenderId(senderId);
      message.setReceiverId(messageDTO.getReceiverId());
      message.setContent(messageDTO.getContent().trim());
      message.setMessageType(messageDTO.getMessageType());
      message.setStatus(1);
      message.setIsDeleted(0);
      message.setCreatedAt(new Date());
      message.setUpdatedAt(new Date());

      // 5. 保存消息
      int rows = messageMapper.insert(message);
      if (rows <= 0) {
        throw new RuntimeException("消息保存失败");
      }

      // 6. 构建返回VO
      return MessageVO.builder()
          .id(message.getId())
          .conversationId(conversationId)
          .senderId(senderId)
          .senderName(sender.getUsername())
          .senderAvatar(sender.getAvatar())
          .receiverId(messageDTO.getReceiverId())
          .receiverName(receiver.getUsername())
          .receiverAvatar(receiver.getAvatar())
          .content(message.getContent())
          .messageType(message.getMessageType())
          .status(message.getStatus())
          .createdAt(message.getCreatedAt())
          .build();
    } catch (Exception e) {
      log.error("发送消息失败", e);
      throw new RuntimeException("发送消息失败: " + e.getMessage());
    }
  }

  @Override
  public List<MessageVO> getUserMessages(Integer userId) {
    // 构建查询条件
    QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("receiverId", userId)
        .or()
        .eq("senderId", userId)
        .eq("isDeleted", 0)
        .orderByDesc("createdAt");

    // 执行查询
    List<Message> messages = messageMapper.selectList(queryWrapper);

    // 无消息时直接返回空列表
    if (messages.isEmpty()) {
      return Collections.emptyList();
    }

    // 获取所有相关用户ID（包括发送者和接收者）
    Set<Integer> userIds = messages.stream()
        .flatMap(msg -> Stream.of(msg.getSenderId(), msg.getReceiverId()))
        .collect(Collectors.toSet());

    // 批量查询用户信息
    Map<Integer, User> userMap = userMapper.selectBatchIds(userIds)
        .stream()
        .collect(Collectors.toMap(User::getId, user -> user));

    // 转换为VO
    return messages.stream().map(msg -> {
      User sender = userMap.get(msg.getSenderId());
      User receiver = userMap.get(msg.getReceiverId());

      return MessageVO.builder()
          .id(msg.getId())
          .conversationId(msg.getConversationId())
          .senderId(msg.getSenderId())
          .senderName(sender != null ? sender.getUsername() : "未知用户")
          .senderAvatar(sender != null ? sender.getAvatar() : null)
          .receiverId(msg.getReceiverId())
          .receiverName(receiver != null ? receiver.getUsername() : "未知用户")
          .receiverAvatar(receiver != null ? receiver.getAvatar() : null)
          .content(msg.getContent())
          .messageType(msg.getMessageType())
          .status(msg.getStatus())
          .readTime(msg.getReadTime())
          .createdAt(msg.getCreatedAt())
          .build();
    }).collect(Collectors.toList());
  }

  @Override
  @Transactional
  public boolean markMessageAsRead(Long messageId, Integer userId) {
    Message message = messageMapper.selectById(messageId);
    if (message == null || !message.getReceiverId().equals(userId)) {
      return false;
    }

    message.setReadTime(new Date());
    message.setStatus(2); // 已读状态
    return messageMapper.updateById(message) > 0;
  }

  @Override
  public List<MessageVO> getConversationMessages(Integer userId, Integer targetUserId) {
    // 构建查询条件
    QueryWrapper<Message> queryWrapper = new QueryWrapper<>();
    queryWrapper.nested(w -> w
        .eq("senderId", userId).eq("receiverId", targetUserId)
        .or()
        .eq("senderId", targetUserId).eq("receiverId", userId))
        .eq("isDeleted", 0)
        .orderByAsc("createdAt");

    // 执行查询
    List<Message> messages = messageMapper.selectList(queryWrapper);

    // 获取用户信息
    User currentUser = userMapper.selectById(userId);
    User targetUser = userMapper.selectById(targetUserId);

    // 转换为VO
    return messages.stream().map(msg -> {
      boolean isCurrentUserSender = msg.getSenderId().equals(userId);

      return MessageVO.builder()
          .id(msg.getId())
          .conversationId(msg.getConversationId())
          .senderId(msg.getSenderId())
          .senderName(isCurrentUserSender ? (currentUser != null ? currentUser.getUsername() : "未知用户")
              : (targetUser != null ? targetUser.getUsername() : "未知用户"))
          .senderAvatar(isCurrentUserSender ? (currentUser != null ? currentUser.getAvatar() : null)
              : (targetUser != null ? targetUser.getAvatar() : null))
          .receiverId(msg.getReceiverId())
          .receiverName(!isCurrentUserSender ? (currentUser != null ? currentUser.getUsername() : "未知用户")
              : (targetUser != null ? targetUser.getUsername() : "未知用户"))
          .receiverAvatar(!isCurrentUserSender ? (currentUser != null ? currentUser.getAvatar() : null)
              : (targetUser != null ? targetUser.getAvatar() : null))
          .content(msg.getContent())
          .messageType(msg.getMessageType())
          .status(msg.getStatus())
          .readTime(msg.getReadTime())
          .createdAt(msg.getCreatedAt())
          .build();
    }).collect(Collectors.toList());
  }

  private String generateConversationId(Integer senderId, Integer receiverId) {
    // 确保较小的ID在前，保证会话ID的唯一性
    return Math.min(senderId, receiverId) + "_" + Math.max(senderId, receiverId);
  }

  @Override
  public Map<String, Object> getPostInteractions(Integer userId, Integer days, Integer page, Integer size) {
    // 参数校验
    if (userId == null || userId <= 0) {
      throw new IllegalArgumentException("用户ID不合法");
    }

    // 查询该用户的所有帖子ID
    QueryWrapper<Post> postQueryWrapper = new QueryWrapper<>();
    postQueryWrapper.eq("authorId", userId)
        .ne("postStatus", 2) // 非删除状态
        .eq("postStatus", 3); // 已发布状态
    List<Post> userPosts = postMapper.selectList(postQueryWrapper);

    if (userPosts.isEmpty()) {
      Map<String, Object> emptyResult = new HashMap<>();
      emptyResult.put("total", 0);
      emptyResult.put("likes", Collections.emptyList());
      emptyResult.put("collects", Collections.emptyList());
      return emptyResult;
    }

    // 收集所有帖子ID
    List<Integer> postIds = userPosts.stream()
        .map(Post::getId)
        .collect(Collectors.toList());

    // 分页查询赞信息
    Page<PostLike> likePage = new Page<>(page, size);
    QueryWrapper<PostLike> likeQueryWrapper = new QueryWrapper<>();
    likeQueryWrapper.in("postId", postIds)
        .eq("status", 1); // 点赞有效

    // 如果指定了天数，则添加时间过滤
    if (days != null && days > 0) {
      Calendar calendar = Calendar.getInstance();
      calendar.add(Calendar.DAY_OF_MONTH, -days);
      Date startDate = calendar.getTime();
      likeQueryWrapper.ge("createTime", startDate);
    }

    likeQueryWrapper.orderByDesc("createTime");
    Page<PostLike> likeResult = postLikeMapper.selectPage(likePage, likeQueryWrapper);

    // 获取点赞详情信息
    List<Map<String, Object>> likeDetails = new ArrayList<>();
    for (PostLike like : likeResult.getRecords()) {
      Map<String, Object> likeDetail = new HashMap<>();

      // 获取点赞者信息
      User liker = userMapper.selectById(like.getUserId());
      if (liker != null) {
        UserVO likerVO = new UserVO();
        BeanUtils.copyProperties(liker, likerVO);
        likeDetail.put("user", likerVO);
      }

      // 获取被点赞的帖子信息
      Post post = postMapper.selectById(like.getPostId());
      if (post != null) {
        PostVO postVO = new PostVO();
        BeanUtils.copyProperties(post, postVO);
        likeDetail.put("post", postVO);
      }

      likeDetail.put("createTime", like.getCreateTime());
      likeDetails.add(likeDetail);
    }

    // 分页查询收藏信息
    Page<PostCollect> collectPage = new Page<>(page, size);
    QueryWrapper<PostCollect> collectQueryWrapper = new QueryWrapper<>();
    collectQueryWrapper.in("postId", postIds)
        .eq("status", 1); // 收藏有效

    // 如果指定了天数，则添加时间过滤
    if (days != null && days > 0) {
      Calendar calendar = Calendar.getInstance();
      calendar.add(Calendar.DAY_OF_MONTH, -days);
      Date startDate = calendar.getTime();
      collectQueryWrapper.ge("createTime", startDate);
    }

    collectQueryWrapper.orderByDesc("createTime");
    Page<PostCollect> collectResult = postCollectMapper.selectPage(collectPage, collectQueryWrapper);

    // 获取收藏详情信息
    List<Map<String, Object>> collectDetails = new ArrayList<>();
    for (PostCollect collect : collectResult.getRecords()) {
      Map<String, Object> collectDetail = new HashMap<>();

      // 获取收藏者信息
      User collector = userMapper.selectById(collect.getUserId());
      if (collector != null) {
        UserVO collectorVO = new UserVO();
        BeanUtils.copyProperties(collector, collectorVO);
        collectDetail.put("user", collectorVO);
      }

      // 获取被收藏的帖子信息
      Post post = postMapper.selectById(collect.getPostId());
      if (post != null) {
        PostVO postVO = new PostVO();
        BeanUtils.copyProperties(post, postVO);
        collectDetail.put("post", postVO);
      }

      collectDetail.put("createTime", collect.getCreateTime());
      collectDetails.add(collectDetail);
    }

    // 组装返回数据
    Map<String, Object> result = new HashMap<>();
    result.put("likes", likeDetails);
    result.put("likesTotal", likeResult.getTotal());
    result.put("collects", collectDetails);
    result.put("collectsTotal", collectResult.getTotal());

    return result;
  }

  @Override
  public Map<String, Object> getRecentFollowers(Integer userId, Integer days, Integer page, Integer size) {
    // 参数校验
    if (userId == null || userId <= 0) {
      throw new IllegalArgumentException("用户ID不合法");
    }

    // 分页查询近期关注该用户的粉丝
    Page<UserFollow> followPage = new Page<>(page, size);
    QueryWrapper<UserFollow> followQueryWrapper = new QueryWrapper<>();
    followQueryWrapper.eq("followedId", userId) // 当前用户是被关注者
        .eq("status", 1); // 关注状态有效

    // 如果指定了天数，则添加时间过滤
    if (days != null && days > 0) {
      Calendar calendar = Calendar.getInstance();
      calendar.add(Calendar.DAY_OF_MONTH, -days);
      Date startDate = calendar.getTime();
      followQueryWrapper.ge("createTime", startDate);
    }

    followQueryWrapper.orderByDesc("createTime");
    Page<UserFollow> followResult = userFollowMapper.selectPage(followPage, followQueryWrapper);

    // 获取关注者详情信息
    List<Map<String, Object>> followerDetails = new ArrayList<>();
    for (UserFollow follow : followResult.getRecords()) {
      Map<String, Object> followerDetail = new HashMap<>();

      // 获取关注者信息
      User follower = userMapper.selectById(follow.getFollowerId());
      if (follower != null) {
        UserVO followerVO = new UserVO();
        BeanUtils.copyProperties(follower, followerVO);
        followerDetail.put("user", followerVO);
      }

      followerDetail.put("createTime", follow.getCreateTime());
      followerDetails.add(followerDetail);
    }

    // 组装返回数据
    Map<String, Object> result = new HashMap<>();
    result.put("followers", followerDetails);
    result.put("total", followResult.getTotal());
    result.put("page", page);
    result.put("size", size);

    return result;
  }

  @Override
  public Map<String, Object> getRecentComments(Integer userId, Integer days, Integer page, Integer size) {
    // 参数校验
    if (userId == null || userId <= 0) {
      throw new IllegalArgumentException("用户ID不合法");
    }

    // 查询该用户的所有帖子ID
    QueryWrapper<Post> postQueryWrapper = new QueryWrapper<>();
    postQueryWrapper.eq("authorId", userId)
        .ne("postStatus", 2) // 非删除状态
        .eq("postStatus", 3); // 已发布状态
    List<Post> userPosts = postMapper.selectList(postQueryWrapper);

    if (userPosts.isEmpty()) {
      Map<String, Object> emptyResult = new HashMap<>();
      emptyResult.put("total", 0);
      emptyResult.put("comments", Collections.emptyList());
      return emptyResult;
    }

    // 收集所有帖子ID
    List<Integer> postIds = userPosts.stream()
        .map(Post::getId)
        .collect(Collectors.toList());

    // 分页查询评论信息
    Page<PostComment> commentPage = new Page<>(page, size);
    QueryWrapper<PostComment> commentQueryWrapper = new QueryWrapper<>();
    commentQueryWrapper.in("postId", postIds)
        .eq("isDeleted", 0);

    // 如果指定了天数，则添加时间过滤
    if (days != null && days > 0) {
      Calendar calendar = Calendar.getInstance();
      calendar.add(Calendar.DAY_OF_MONTH, -days);
      Date startDate = calendar.getTime();
      commentQueryWrapper.ge("createTime", startDate);
    }

    commentQueryWrapper.orderByDesc("createTime");
    Page<PostComment> commentResult = postCommentMapper.selectPage(commentPage, commentQueryWrapper);

    // 获取评论详情信息
    List<Map<String, Object>> commentDetails = new ArrayList<>();
    for (PostComment comment : commentResult.getRecords()) {
      Map<String, Object> commentDetail = new HashMap<>();

      // 获取评论者信息
      User commenter = userMapper.selectById(comment.getUserId());
      if (commenter != null) {
        UserVO commenterVO = new UserVO();
        BeanUtils.copyProperties(commenter, commenterVO);
        commentDetail.put("user", commenterVO);
      }

      // 获取被评论的帖子信息
      Post post = postMapper.selectById(comment.getPostId());
      if (post != null) {
        PostVO postVO = new PostVO();
        BeanUtils.copyProperties(post, postVO);
        commentDetail.put("post", postVO);
      }

      // 评论内容
      commentDetail.put("content", comment.getCommentText());
      commentDetail.put("createTime", comment.getCreateTime());

      // 如果是回复其他评论
      if (comment.getParentCommentId() != null && comment.getParentCommentId() > 0) {
        PostComment replyComment = postCommentMapper.selectById(comment.getParentCommentId());
        if (replyComment != null) {
          PostCommentVO replyVO = new PostCommentVO();
          BeanUtils.copyProperties(replyComment, replyVO);

          // 获取被回复者信息
          User repliedUser = userMapper.selectById(replyComment.getUserId());
          if (repliedUser != null) {
            UserVO repliedUserVO = new UserVO();
            BeanUtils.copyProperties(repliedUser, repliedUserVO);
            commentDetail.put("repliedUser", repliedUserVO);
          }

          commentDetail.put("replyComment", replyVO);
        }
      }

      commentDetails.add(commentDetail);
    }

    // 组装返回数据
    Map<String, Object> result = new HashMap<>();
    result.put("comments", commentDetails);
    result.put("total", commentResult.getTotal());
    result.put("page", page);
    result.put("size", size);

    return result;
  }
}
